package org.babygo.connect.handler.code;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.UnpooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import org.babygo.connect.protocol.GetAndSendFileRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DecodeInHandler extends ChannelInboundHandlerAdapter{
	private Logger log = LoggerFactory.getLogger(DecodeInHandler.class);

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		log.info("DECODE来自服务器发送文件的请求");
		ByteBuf buf = (ByteBuf)msg;
		int lineFeedIndex = buf.bytesBefore((byte)10);
		byte[] protocol = new byte[lineFeedIndex];
		buf.readBytes(protocol, 0, lineFeedIndex);
		String message = new String(protocol);
		GetAndSendFileRequest andSendFileRequest = new GetAndSendFileRequest(message, true);
		ctx.fireChannelRead(andSendFileRequest);
	}

	public static String bytes2HexString(byte[] b) {  
	    String ret = "";
	    for (int i = 0; i < b.length; i++) {  
	        String hex = Integer.toHexString(b[ i ] & 0xFF);  
	    if (hex.length() == 1) {  
	        hex = '0' + hex;  
	    }  
	     ret += hex.toUpperCase();  
	  }  
	  return ret;  
	}  
	
	public static void main(String[] args) {
		UnpooledByteBufAllocator all = new UnpooledByteBufAllocator(true);
		ByteBuf buf = all.directBuffer(10);
		byte[] bb = new byte[]{(byte) 0x55,(byte) 0xFE,(byte) 0xFF,(byte) 0xFF};
		byte[] cc = new String("abcsa").getBytes();
		byte[] b = new byte[10];
		int f = 0;
		for (int i = 0; i < bb.length; i++) {
				b[f] = bb[i];
				f++;
		}
		for (int i = 0; i < cc.length; i++) {
			b[f] = cc[i];
			f++;
		}

		buf.writeBytes(b);
		ByteBuf buf1 = buf;
		if (buf.isReadable()){
//			buf.markReaderIndex();
			ByteBuf newbuf = buf1.readBytes(9);
			System.out.println(buf1.readerIndex());
			System.out.println(buf1.isReadable());
			System.out.println(buf.readerIndex());
			System.out.println(newbuf.bytesBefore((byte) 0xFF));
//			buf.resetReaderIndex();
			byte[] a = newbuf.array();
//			for (int i = 0; i < a.length; i++) {
				System.out.println(bytes2HexString(a));
//			}
		}
//		System.out.println(bytes2HexString(new byte[]{b}));
//		System.out.println(Integer.toHexString(b));
//		System.out.println(Integer.parseInt("FE",16));
	}
}